/**
 * Created by Administrator on 2016/12/16.
 */
/***加载 数据 到表格*****/
$(function () {
    init();
    uploadImg();
    $('.addTeam,.dealAll').addClass("disabled");
})
function init() {
    $.ajax({
        type: "get",
        contentType: 'application/json',
        url: 'http://192.168.59.3:8082/console/basedata/projectType/getAllProjectTypeList',
        success: function (data) {
            console.log(data);
            var oHtml = "";
            console.log(data.data.length);
            for (var i = 0; i < data.data.length; i++) {
                oHtml += `<option value=${data.data[i].id}>${data.data[i].projectType}</option>`
            }
            $("[data-name='projectType']").html(oHtml);
        }
    })
}
function responseHandler(res) {
    var needData = {
        rows: res.data.list,
        total: res.data.total
    }
    return needData;
}
function teamTableQuery(params) {
    params['pageNum'] = (params.offset / params.limit) + 1;
    params.pageSize = params.limit;
    return params;
}
function addRemoveFmt(index, row, val) {
    return "<button class='btn btn-default'>查看/编辑</button>"

}
/**********日期选择插件**********/
$(".form-date").datetimepicker(
    {
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: "yyyy-mm-dd"
    });

/***********
 * *************/

//////////////////////////////////////////
///////////////封装ajax //////////////////////////
function sendDigital(type, url, data) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        contentType: 'application/json',
        success: function (data) {
           // console.log(data);
            localStorage.contractor = data;
        },
        error: function (err) {
            console.log(err);
        }
    });
}
/****点击项目承包人input框，弹出项目承包人列表页面*****/
$('input[data-name="contractorName"]').focus(function () {
    console.log(1);
    sendDigital('post', `http://192.168.59.3:8082/console/projectInfo/findUserListByRole`, '{"pageNum":1,"pageSize":6,"roleId":3}');
    layer.open({
        title: "项目承包人列表",
        type: 2,
        area: ['50%', '50%'],
        maxmin: true,
        fix: false,
        shadeClose: true,
        content: `../addProject/contractor/contractor.html`
    });
    //console.log(localStorage.getItem("realName"));
});
$('input[data-name="contractorName"]').blur(function () {
    //$(this).val(sessionStorage.getItem("realName"));
    //sessionStorage.clear('realName');
    var moved = 0;
    var timer = setInterval(function () {
        moved++;
        if (sessionStorage.getItem("realName")) {
            this.value = sessionStorage.getItem("realName");
            clearInterval(timer);
            timer = null;
            sessionStorage.clear('realName');
        }
        if (moved >= 3) {
            clearInterval(timer);
            timer = null;
        }
    }.bind(this), 50)
})
/****点击承包单位input框，弹出承包单位列表页面*****/
$('input[data-name="constructionUnit"]').focus(function () {
    console.log(1);
    sendDigital('post', `http://192.168.59.3:8082/console/projectInfo/findCompanyByRole`, '{"pageNum":1,"pageSize":6,"roleId":4}');
    layer.open({
        title: "承包单位列表",
        type: 2,
        area: ['50%', '50%'],
        maxmin: true,
        fix: false,
        shadeClose: true,
        content: `../addProject/constructionUnit/constructionUnit.html`
    });
    console.log(localStorage.getItem("realName"));
    $(this).val(localStorage.getItem("realName"))
});

/*********点击确定按钮，将信息保存到后台****************/
$('.resure').click(function () {
    resure();

});
// $('input[type="text"]');
/******封装 ---获取页面填写信息并发送*********/
function resure() {
    var oIpt = $('[data-name]');
    console.log(oIpt);
    var str = {};
    for (var i = 0; i < oIpt.length; i++) {
        //console.log(($(oIpt[i]).attr('data-name')));
        //console.log(oIpt[i].nodeName);
        if (oIpt[i].nodeName == "INPUT") {
            str[$(oIpt[i]).attr('data-name')] = $(oIpt[i]).val();
        };
        //console.log($(oIpt[i]).attr("data-name") == "contractorAuthorization");

        if ($(oIpt[i]).attr("data-name") == "contractorAuthorization") {
            var oA="";
            var a1=$(oIpt[i]).find("input[type='file']");
            console.log(a1);
            a1.each(function(i,e){
                if(e.files[0]){
                    console.log(e.files[0].name);
                    oA+="imgs/"+e.files[0].name+",";
                }
            })
            oA = oA.slice(0,oA.length-1);
            console.log(oA);
            str["contractorAuthorization"]=oA;
        };
        if ($(oIpt[i]).attr("data-name") == "constructAuthorization") {
            var oB="";
            var b1=$(oIpt[i]).find("input[type='file']");
            b1.each(function(i,e){
                if(e.files[0]){
                    oB+="imgs/"+e.files[0].name+",";
                }
            })
            oB = oB.slice(0,oB.length-1);

            str["constructAuthorization"]=oB;
            console.log(oB);
        };

    }
    str['projectStart'] = new Date(str.projectStart).getTime();
   // str['id']=json.id;
    console.log(JSON.stringify(str));
    $.ajax({
        type: "post",
        url: `http://192.168.59.3:8082/console/projectInfo/saveProjectInfo`,
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify(str),
        success: function (data) {
            console.log(data);

            $('.addTeam,.dealAll').removeClass("btn-default");
            $('.addTeam').addClass("btn-warning");
            $('.dealAll').addClass("btn-info");
            $('.addTeam,.dealAll').removeClass("disabled");
            layerIfr("项目列表/项目基本资料/新增项目/新增分包班组",`../addTeams/addTeams.html?projectCode=${data.data}`);
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            //parent.layer.close(index);
        },
        error: function (err) {
            console.log(err);
            layer.open({
                title: "提示",
                type: 1,
                area: ['20%', '20%'],
                maxmin: true,
                fix: false,
                shadeClose: true,
                content: `<h4 style="text-align: center;">请填写完整信息！</h4>`
            });
        }
    });
}
/********点击新增班组 用layer弹出新页面****************/
function layerIfr(title, url) {
    layer.open({
        title: title,
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: url
    })
}

$('.addTeam').click(function () {
   /* var oIpt = $('[data-name]');
    console.log(oIpt);
    var str = {};
    for (var i = 0; i < oIpt.length; i++) {
        //console.log(($(oIpt[i]).attr('data-name')));
        str[$(oIpt[i]).attr('data-name')] = $(oIpt[i]).val();
    }
    str['projectStart'] = new Date(str.projectStart).getTime()
    console.log(JSON.stringify(str));
*/
        //resure();
    layerIfr("项目列表/项目基本资料/新增项目/新增分包班组",`../addTeams/addTeams.html`);

});


////*********上传图片************///
function uploadImg() {
    var host = "http://192.168.59.2:7090/image";
    var firstName = "http://choosefine-uat.oss-cn-hangzhou.aliyuncs.com/";

    if ($('[data-pic]')) {
        $('[data-pic]')

            .html(`
            <img src="#">
            <form action=${host} method="post" enctype="multipart/form-data" target="hide_frame" style="display: none;">
              <input name="name">
              <input type="file" name="file"/>
            <form>
          `)
            .find('[type="file"]').on('change',
            function () {
                var lastName = "console/user/" + (new Date()).getTime() + '-' + this.files[0].name;
                $(this).prev().val(lastName);
                $(this).parent().submit();
                console.log(firstName + lastName);
                setTimeout(function () {
                    $(this).parent().prev().attr('src', firstName + lastName);
                }.bind(this), 12000)
            });
        $('[data-pic]')
            .each(function (i, div) {
                var dataName = $(div).attr('data-pic');

                $(div).find('img').attr('data-name', dataName)
            });

        $('[data-pic]').find('img')

            .on('click', function () {
                $(this).parent().find('[type="file"]').click();
            })

        $(document.body).append(`
            <iframe name="hide_frame" style="display: none">
          `)
    }

    if ($("[data-purl]")) {
        var images = $("[data-purl]").find('img');
        var purl = "";

        images.each(function (i, img) {
            purl = $(img).parent().attr('data-purl');
            $(img).attr('src', purl);
        })
    }
}

